package com.zjy.financialsystemjavafx.service;

import com.zjy.financialsystemjavafx.model.entity.User;
import com.zjy.financialsystemjavafx.util.DatabaseUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.LocalDateTime;

/**
 * 用户服务层，提供登录验证功能
 */
public class UserService {
    private final DataSource dataSource;

    public UserService() {
        this.dataSource = DatabaseUtil.getDataSource();
    }

    /**
     * 验证用户名和密码
     * @return 登录成功返回 User，否则返回 null
     */
    public User authenticate(String username, String password) throws Exception {
        String sql = "SELECT user_id, username, password_hash, email, phone_number, created_at, last_login " +
                     "FROM users WHERE username = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    String storedHash = rs.getString("password_hash");
                    // 简单比较，实际可使用 Hash 工具
                    if (storedHash.equals(password)) {
                        int userId = rs.getInt("user_id");
                        String email = rs.getString("email");
                        String phone = rs.getString("phone_number");
                        LocalDateTime created = rs.getTimestamp("created_at").toLocalDateTime();
                        Timestamp lastLoginTs = rs.getTimestamp("last_login");
                        LocalDateTime lastLogin = lastLoginTs != null ? lastLoginTs.toLocalDateTime() : null;
                        User user = new User(userId, username, storedHash, email, phone, created, lastLogin);
                        updateLastLogin(userId);
                        return user;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 更新最后登录时间
     */
    private void updateLastLogin(int userId) throws Exception {
        String sql = "UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.executeUpdate();
        }
    }

    /**
     * 注册新用户
     * @return 注册成功返回 true，否则 false
     */
    public boolean register(String username, String password, String email, String phone) throws Exception {
        String sql = "INSERT INTO users (username, password_hash, email, phone_number) VALUES (?, ?, ?, ?)";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, username);
            ps.setString(2, password);
            ps.setString(3, email);
            ps.setString(4, phone);
            int rows = ps.executeUpdate();
            return rows > 0;
        }
    }

    /**
     * 更新用户个人信息
     */
    public boolean updateUserInfo(int userId, String email, String phone) throws Exception {
        String sql = "UPDATE users SET email = ?, phone_number = ? WHERE user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setString(1, email);
            ps.setString(2, phone);
            ps.setInt(3, userId);
            return ps.executeUpdate() > 0;
        }
    }

    /**
     * 修改用户密码（简单比较明文），实际项目建议使用安全哈希
     */
    public boolean changePassword(int userId, String oldPassword, String newPassword) throws Exception {
        // 验证旧密码
        String select = "SELECT password_hash FROM users WHERE user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(select)) {
            ps.setInt(1, userId);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    String stored = rs.getString("password_hash");
                    if (!stored.equals(oldPassword)) {
                        return false;
                    }
                } else {
                    return false;
                }
            }
        }
        // 更新为新密码
        String update = "UPDATE users SET password_hash = ? WHERE user_id = ?";
        try (Connection conn = dataSource.getConnection();
             PreparedStatement ps = conn.prepareStatement(update)) {
            ps.setString(1, newPassword);
            ps.setInt(2, userId);
            return ps.executeUpdate() > 0;
        }
    }
} 